package com.wwwarehouse.usercenter.fragment.permissiondistribute;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleCompleteEvent;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.authoritydistribute.AuthProcessUkidBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.AuthorityDistributeItemBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.AuthorityWrapItemBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.DistributeResultBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.PowerDistributeBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import de.greenrobot.event.EventBus;


/**
 * @author : mundane
 * @time : 2017/9/19 20:35
 * @description :
 * @file : BRCFDTagsFragment.java
 */

@Route(path = UserCenterConstant.PATH_AUTHORITY_DISTRIBUTE)
public class AuthorityDistributePagerFragment extends BaseFragment implements AuthorityDistributeListFragment.OnButtonClickedListener {

    private CustomViewPagerInternal      mCustomViewPagerInternal;
    private CirclePageIndicator          mCirclePagerIndicator;
    private List<Fragment>               mFragmentList;
    private SelectPermissionPagerAdapter mViewPagerAdapter;
    private ElasticScrollView            mElasticScrollView;
    private List<FilterBean>             mFilterList;
    private int mSelectedBubblePosition = 2;
    private Button                                 mBtnDistribute;
    private String                                 mBusinessUnitId;
    private List<AuthorityDistributeItemBean>      mAuthorityAllDataList;
    private List<ArrayList<AuthorityWrapItemBean>> mFragmentDataList;
    private ArrayList<AuthorityDistributeItemBean> mSelectedDataList;
    private int                                    mListSize;
    private TreeSet<String>                        mTagHashSet;
    private List<AuthorityDistributeItemBean> mAuthorLinkedList  = new ArrayList<>();
    private NoHttpUtils.OnResponseListener    onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            try {
                switch (what) {
                    case 0:
                        if (TextUtils.equals("0", commonClass.getCode())) {
                            mStateLayout.showContentView();
                            mAuthorityAllDataList = JSON.parseArray(commonClass.getData().toString(), AuthorityDistributeItemBean.class);

                            /******** 设置侧滑菜单 *******/
                            for (AuthorityDistributeItemBean bean : mAuthorityAllDataList) {
                                mTagHashSet.add(bean.tagName);
                            }
                            for (String tag : mTagHashSet) {
                                mFilterList.add(new FilterBean(false, tag));
                            }
                            DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance("权限标签", mFilterList, 2);
                            ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                            ((BaseCardDeskActivity) mActivity).disableDrawerLayout();
                            /******** 设置侧滑菜单 *******/

                            mAuthorLinkedList.addAll(mAuthorityAllDataList);
                            // 默认排序：获取权限时间由近到远
                            Collections.sort(mAuthorLinkedList, new Comparator<AuthorityDistributeItemBean>() {
                                @Override
                                public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                    Date date1 = DateUtil.formatDateStr(o1.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = DateUtil.formatDateStr(o2.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    if (date1.after(date2)) {
                                        return -1;
                                    } else if (date1.before(date2)) {
                                        return 1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });
                            mListSize = mAuthorLinkedList.size();
                            mActivity.setTitle(String.format("权限分配(%d)", mListSize));
                            // 分页
                            List<AuthorityDistributeItemBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是27
                            for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                                list.add(mAuthorLinkedList.get(i));
                                if (list.size() == 27 || i == mAuthorLinkedList.size() - 1) { // 当填满了27个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                                    ArrayList<AuthorityWrapItemBean> perPageList = new ArrayList<>();
                                    for (AuthorityDistributeItemBean itemBean : list) {
                                        perPageList.add(new AuthorityWrapItemBean(itemBean));
                                    }
                                    mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                                    list = new ArrayList<>(); // 清空填装item的容器
                                }
                            }

                            for (ArrayList<AuthorityWrapItemBean> dataList : mFragmentDataList) {
                                AuthorityDistributeListFragment listFragment = AuthorityDistributeListFragment.newInstance(dataList);
                                listFragment.setOnButtonClickedListener(AuthorityDistributePagerFragment.this);
                                mFragmentList.add(listFragment);
                            }
                            mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                            mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                            mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                            refreshButtonState();


                        } else {
                            ToastUtils.showToast(commonClass.getMsg());
                        }
                        break;
                    case 1:
                        if (TextUtils.equals("0", commonClass.getCode())) {
                            AuthProcessUkidBean authProcessUkidBean = JSON.parseObject(commonClass.getData().toString(), AuthProcessUkidBean.class);
                            //                        popFragment();
                            pushFragment(AuthorityDistributeQRcodeFragment.newInstance(authProcessUkidBean, mBusinessUnitId, mSelectedDataList));
                        } else if (TextUtils.equals("200201", commonClass.getCode())) { // 权限生效、失效时间配置错误
                            PermissionNotFoundFragment fragment = new PermissionNotFoundFragment();
                            Bundle bundle = new Bundle();
                            bundle.putInt(PermissionNotFoundFragment.KEY_TYPE, 0);
                            fragment.setArguments(bundle);
                            //                        popFragment();
                            pushFragment(fragment);
                        } else if (TextUtils.equals("210018", commonClass.getCode())) { // 授权人的权限发生变化
                            PermissionNotFoundFragment fragment = new PermissionNotFoundFragment();
                            Bundle bundle = new Bundle();
                            bundle.putInt(PermissionNotFoundFragment.KEY_TYPE, 1);
                            fragment.setArguments(bundle);
                            //                        popFragment();
                            pushFragment(fragment);
                        } else {
                            ToastUtils.showToast(commonClass.getMsg());
                        }
                        break;
                    case 2:
                        if ("0".equals(commonClass.getCode())) {
                            PowerDistributeBean powerDistributeBean = JSON.parseObject(commonClass.getData().toString(), PowerDistributeBean.class);
                            int status = powerDistributeBean.getStatus();
                            //（0成功， 1失败， 2 部分成功， 3 异常）
                            switch (status) {
                                case 0:
                                    PermissionDistributeSuccessFragment fragment = new PermissionDistributeSuccessFragment();
                                    Bundle bundle = new Bundle();
                                    DistributeResultBean bean = new DistributeResultBean();
                                    bean.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean = new DistributeResultBean.DetailBean();
                                    detailBean.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean.setDetail(detailBean);
                                    bean.setDescription(powerDistributeBean.getDescription());
                                    bean.setStatus(powerDistributeBean.getStatus());
                                    bundle.putParcelable("resultBean", bean);
                                    bundle.putString("type", "CheckDownClassFragment");
                                    bundle.putString("personName", mPersonName);
                                    bundle.putString("userId", mUserId);
                                    bundle.putString("buId", mBusinessUnitId);
                                    fragment.setArguments(bundle);
                                    pushFragment(fragment);
                                    break;
                                case 1:
                                    PermissionDistributeAllErrorFragment fragment1 = new PermissionDistributeAllErrorFragment();
                                    Bundle bundle1 = new Bundle();
                                    DistributeResultBean bean1 = new DistributeResultBean();
                                    bean1.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean1 = new DistributeResultBean.DetailBean();
                                    detailBean1.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean1.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean1.setDetail(detailBean1);
                                    bean1.setDescription(powerDistributeBean.getDescription());
                                    bean1.setStatus(powerDistributeBean.getStatus());
                                    bundle1.putParcelable("resultBean", bean1);
                                    bundle1.putString("type", "CheckDownClassFragment");
                                    bundle1.putString("personName", mPersonName);
                                    bundle1.putString("userId", mUserId);
                                    bundle1.putString("buId", mBusinessUnitId);
                                    fragment1.setArguments(bundle1);
                                    pushFragment(fragment1);

                                    break;
                                case 2:
                                    PermissionDistributeAnySuccessFragment fragment2 = new PermissionDistributeAnySuccessFragment();
                                    Bundle bundle2 = new Bundle();
                                    DistributeResultBean bean2 = new DistributeResultBean();
                                    bean2.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean2 = new DistributeResultBean.DetailBean();
                                    detailBean2.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean2.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean2.setDetail(detailBean2);
                                    bean2.setDescription(powerDistributeBean.getDescription());
                                    bean2.setStatus(powerDistributeBean.getStatus());
                                    bundle2.putParcelable("resultBean", bean2);
                                    bundle2.putString("type", "CheckDownClassFragment");
                                    bundle2.putString("personName", mPersonName);
                                    bundle2.putString("userId", mUserId);
                                    bundle2.putString("buId", mBusinessUnitId);
                                    fragment2.setArguments(bundle2);
                                    pushFragment(fragment2);

                                    break;
                                case 3:
                                    PermissionAddressNotFoundFragment fragment3 = new PermissionAddressNotFoundFragment();
                                    Bundle bundle3 = new Bundle();
                                    if (powerDistributeBean.getCardNames().size() == 0) {
                                        bundle3.putString("content", mActivity.getResources().getString(R.string.permission_description_txt));
                                    } else if (powerDistributeBean.getCardNames().size() == 1) {
                                        bundle3.putString("content", powerDistributeBean.getCardNames().get(0) + mActivity.getResources().getString(R.string.permission_description_txt));
                                    } else if (powerDistributeBean.getCardNames().size() > 1) {
                                        bundle3.putString("content", powerDistributeBean.getCardNames().get(0) + mActivity.getResources().getString(R.string.user_pr_etc) + mActivity.getResources().getString(R.string.permission_description_txt));
                                    }
                                    bundle3.putString("type", "CheckDownClassFragment");
                                    bundle3.putString("personName", mPersonName);
                                    bundle3.putString("userId", mUserId);
                                    bundle3.putString("buId", mBusinessUnitId);
                                    fragment3.setArguments(bundle3);
                                    pushFragment(fragment3);

                                    break;
                            }
                        }

                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                LogUtils.showLog(e.toString());
            }

        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
    private StateLayout mStateLayout;
    private ArrayList   mUserIdList;
    private String      mUserId;
    private String      mPersonName;


    public static AuthorityDistributePagerFragment newInstance(String businessUnitId) {
        AuthorityDistributePagerFragment fragment = new AuthorityDistributePagerFragment();
        Bundle args = new Bundle();
        args.putString(UserCenterConstant.KEY_BUSINESS_UNIT_ID, businessUnitId);
        fragment.setArguments(args);
        return fragment;
    }

    public void onEventMainThread(DrawerMultipleCompleteEvent event) {
        if (!(peekFragment() instanceof AuthorityDistributePagerFragment)) {
            return;
        }
        ((BaseCardDeskActivity) mActivity).hideDrawerLayout();
        Set<Integer> set = event.getSelectedPositionSet();
        List<String> filterBeanList = new ArrayList<>();
        if (set.isEmpty()) {
            for (FilterBean filterBean : mFilterList) {
                filterBeanList.add(filterBean.getText());
            }
        } else {
            for (Integer i : set) {
                filterBeanList.add(mFilterList.get(i).getText());
            }
        }
        mAuthorLinkedList.clear();
        for (AuthorityDistributeItemBean itemBean : mAuthorityAllDataList) {
            if (filterBeanList.contains(itemBean.tagName)) {
                mAuthorLinkedList.add(itemBean);
            }
        }

        mFragmentDataList.clear();
        // 分页
        List<AuthorityDistributeItemBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是27
        for (int i = 0; i < mAuthorLinkedList.size(); i++) {
            list.add(mAuthorLinkedList.get(i));
            if (list.size() == 27 || i == mAuthorLinkedList.size() - 1) { // 当填满了27个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                ArrayList<AuthorityWrapItemBean> perPageList = new ArrayList<>();
                for (AuthorityDistributeItemBean itemBean : list) {
                    perPageList.add(new AuthorityWrapItemBean(itemBean));
                }
                mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                list = new ArrayList<>(); // 清空填装item的容器
            }
        }
        mFragmentList.clear();
        for (ArrayList<AuthorityWrapItemBean> dataList : mFragmentDataList) {
            AuthorityDistributeListFragment listFragment = AuthorityDistributeListFragment.newInstance(dataList);
            listFragment.setOnButtonClickedListener(AuthorityDistributePagerFragment.this);
            mFragmentList.add(listFragment);
        }
        mCustomViewPagerInternal.removeAllViews();
        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
        mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
        mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
        mCirclePagerIndicator.requestLayout();
        mViewPagerAdapter.notifyDataSetChanged();
        refreshButtonState();

    }

    private boolean isFromTeam;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            if (!TextUtils.isEmpty(bundle.getString("CheckDownClassFragment"))) {
                //                bundle.putString("personName", mBean1.getPersonName());
                //                bundle.putString("userId", mBean1.getUserId());
                //                bundle.putString("buId", buId);
                isFromTeam = true;
                mPersonName = bundle.getString("personName");
                mBusinessUnitId = bundle.getString("buId");
                mUserId = bundle.getString("userId");
                sp.putValue(UserCenterConstant.SAVE_BUSINESSUNITID, mBusinessUnitId);
            } else {
                //			mBusinessUnitId = bundle.getString(UserCenterConstant.KEY_BUSINESS_UNIT_ID);
                CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
                mBusinessUnitId = taskBean.getBusinessId();
                sp.putValue(UserCenterConstant.SAVE_BUSINESSUNITID, mBusinessUnitId);
            }

        }
        mFragmentList = new ArrayList<>();
        mFilterList = new ArrayList<>();
        mFragmentDataList = new ArrayList<>();
        mSelectedDataList = new ArrayList<>();
        mTagHashSet = new TreeSet<>();
        mUserIdList = new ArrayList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pager_distribute_authority, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // findViewById
        mCustomViewPagerInternal = $(R.id.cvpi);
        mCirclePagerIndicator = $(R.id.cpi);
        mElasticScrollView = $(R.id.esv);
        mBtnDistribute = $(R.id.btn_distribute);
        mStateLayout = $(R.id.slt);

        mBtnDistribute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final SetAuthorityTimeDialogFragment dialogFragment = SetAuthorityTimeDialogFragment.newInstance();
                dialogFragment.setTitle("设置权限授权期")
                        .setMessage("设置了授权期的权限,在授权期外将自动收回该权限。")
                        .setOnCancelClickListener(new SetAuthorityTimeDialogFragment.onCancelClickListener() {
                            @Override
                            public void onCancelClick(View view, DialogFragment dialog) {
                                dialogFragment.dismiss();
                                if (isFromTeam) {
                                    Map<String, Object> map = new HashMap<>();
                                    mUserIdList.clear();
                                    map.put("businessUnitId", mBusinessUnitId);
                                    mUserIdList.add(mUserId);
                                    map.put("selectedUserIds", mUserIdList);
                                    List<Long> cardAuthUkidLists = new ArrayList<>();
                                    for (AuthorityDistributeItemBean itemBean : mSelectedDataList) {
                                        cardAuthUkidLists.add(itemBean.userCardAuthorityUkid);
                                    }
                                    map.put("userCardAuthorityUkids", cardAuthUkidLists);
                                    showProgressDialog();
                                    NoHttpUtils.httpPost(UserCenterConstant.TEAM_BATCH_ADD_AUTHOR, map, onResponseListener, 2);
                                } else {
                                    Date currentDate = new Date();
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("authStart", sdf.format(currentDate));
                                    // 结束时间排序, 从早到晚
                                    Collections.sort(mSelectedDataList, new Comparator<AuthorityDistributeItemBean>() {
                                        @Override
                                        public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                            Date date1 = DateUtil.formatDateStr(o1.invalidDateStr, "yyyy-MM-dd HH:mm:ss");
                                            Date date2 = DateUtil.formatDateStr(o2.invalidDateStr, "yyyy-MM-dd HH:mm:ss");
                                            return date1.before(date2) ? -1 : 1;
                                        }
                                    });
                                    String endTime = mSelectedDataList.get(0).invalidDateStr;
                                    map.put("authEnd", endTime);
                                    map.put("businessId", mBusinessUnitId);
                                    List<Long> cardAuthUkidList = new ArrayList<>();
                                    for (AuthorityDistributeItemBean itemBean : mSelectedDataList) {
                                        cardAuthUkidList.add(itemBean.userCardAuthorityUkid);
                                    }
                                    map.put("cardAuthUkids", cardAuthUkidList);
                                    showProgressDialog();
                                    NoHttpUtils.httpPost(UserCenterConstant.GET_AUTH_PROCESS_UKID, map, onResponseListener, 1);
                                }

                            }
                        })
                        .setOnConfirmClickListener(new SetAuthorityTimeDialogFragment.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view) {

                                // 起始时间排序, 从晚到早
                                Collections.sort(mSelectedDataList, new Comparator<AuthorityDistributeItemBean>() {
                                    @Override
                                    public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                        Date date1 = DateUtil.formatDateStr(o1.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                        Date date2 = DateUtil.formatDateStr(o2.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                        return date1.after(date2) ? -1 : 1;
                                    }
                                });
                                String startTime = mSelectedDataList.get(0).validDateStr;
                                // 结束时间排序, 从早到晚
                                Collections.sort(mSelectedDataList, new Comparator<AuthorityDistributeItemBean>() {
                                    @Override
                                    public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                        Date date1 = DateUtil.formatDateStr(o1.invalidDateStr, "yyyy-MM-dd HH:mm:ss");
                                        Date date2 = DateUtil.formatDateStr(o2.invalidDateStr, "yyyy-MM-dd HH:mm:ss");
                                        return date1.before(date2) ? -1 : 1;
                                    }
                                });
                                String endTime = mSelectedDataList.get(0).invalidDateStr;
                                dialogFragment.dismiss();
                                if (isFromTeam) {
                                    mUserIdList.clear();
                                    mUserIdList.add(mUserId);
                                    pushFragment(AuthoritySetTimeFragment.newInstance(startTime, endTime, mBusinessUnitId, mSelectedDataList, mUserIdList));
                                } else {
                                    pushFragment(AuthoritySetTimeFragment.newInstance(startTime, endTime, mBusinessUnitId, mSelectedDataList));

                                }
                            }
                        });
                dialogFragment.show(getFragmentManager(), "");

            }
        });

        cardDeskOption();
    }

    private void cardDeskOption() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });

    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof AuthorityDistributePagerFragment) {

            List<AuthorityDistributeItemBean> tempList = new ArrayList<>();
            for (AuthorityDistributeItemBean itemBean : mAuthorLinkedList) {
                if (itemBean.cardName.contains(text)) {
                    tempList.add(itemBean);
                }
            }

            mFragmentDataList.clear();
            // 分页
            List<AuthorityDistributeItemBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是27
            for (int i = 0; i < tempList.size(); i++) {
                list.add(tempList.get(i));
                if (list.size() == 27 || i == tempList.size() - 1) { // 当填满了27个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                    ArrayList<AuthorityWrapItemBean> perPageList = new ArrayList<>();
                    for (AuthorityDistributeItemBean itemBean : list) {
                        perPageList.add(new AuthorityWrapItemBean(itemBean));
                    }
                    mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                    list = new ArrayList<>(); // 清空填装item的容器
                }
            }
            mFragmentList.clear();
            for (ArrayList<AuthorityWrapItemBean> dataList : mFragmentDataList) {
                AuthorityDistributeListFragment listFragment = AuthorityDistributeListFragment.newInstance(dataList);
                listFragment.setOnButtonClickedListener(AuthorityDistributePagerFragment.this);
                mFragmentList.add(listFragment);
            }
            mCustomViewPagerInternal.removeAllViews();
            mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
            mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
            mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
            mCirclePagerIndicator.requestLayout();
            mViewPagerAdapter.notifyDataSetChanged();
            refreshButtonState();
        }
    }


    @Override
    public void filterClick() {
        if (peekFragment() instanceof AuthorityDistributePagerFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    @Override
    public void cancelClick() {
        if (peekFragment() instanceof AuthorityDistributePagerFragment) {
            mFragmentDataList.clear();
            // 分页
            List<AuthorityDistributeItemBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是27
            for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                list.add(mAuthorLinkedList.get(i));
                if (list.size() == 27 || i == mAuthorLinkedList.size() - 1) { // 当填满了27个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                    ArrayList<AuthorityWrapItemBean> perPageList = new ArrayList<>();
                    for (AuthorityDistributeItemBean itemBean : list) {
                        perPageList.add(new AuthorityWrapItemBean(itemBean));
                    }
                    mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                    list = new ArrayList<>(); // 清空填装item的容器
                }
            }
            mFragmentList.clear();
            for (ArrayList<AuthorityWrapItemBean> dataList : mFragmentDataList) {
                AuthorityDistributeListFragment listFragment = AuthorityDistributeListFragment.newInstance(dataList);
                listFragment.setOnButtonClickedListener(AuthorityDistributePagerFragment.this);
                mFragmentList.add(listFragment);
            }
            mCustomViewPagerInternal.removeAllViews();
            mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
            mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
            mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
            mViewPagerAdapter.notifyDataSetChanged();
            refreshButtonState();
        }
    }

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof AuthorityDistributePagerFragment) {
            PopUpUtils.showBubbleAuthoritySort(getContext(), anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    mSelectedBubblePosition = position;

                    switch (position) {
                        case 1:
                            // 获取权限时间由远到近
                            Collections.sort(mAuthorLinkedList, new Comparator<AuthorityDistributeItemBean>() {
                                @Override
                                public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                    Date date1 = DateUtil.formatDateStr(o1.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = DateUtil.formatDateStr(o2.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    if (date1.after(date2)) {
                                        return 1;
                                    } else if (date1.before(date2)) {
                                        return -1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });
                            break;
                        case 2:
                            // 获取权限时间由近到远
                            Collections.sort(mAuthorLinkedList, new Comparator<AuthorityDistributeItemBean>() {
                                @Override
                                public int compare(AuthorityDistributeItemBean o1, AuthorityDistributeItemBean o2) {
                                    Date date1 = DateUtil.formatDateStr(o1.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = DateUtil.formatDateStr(o2.validDateStr, "yyyy-MM-dd HH:mm:ss");
                                    if (date1.after(date2)) {
                                        return -1;
                                    } else if (date1.before(date2)) {
                                        return 1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });

                            break;
                        default:
                            break;
                    }
                    mFragmentDataList.clear();
                    // 分页
                    List<AuthorityDistributeItemBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是27
                    for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                        list.add(mAuthorLinkedList.get(i));
                        if (list.size() == 27 || i == mAuthorLinkedList.size() - 1) { // 当填满了27个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                            ArrayList<AuthorityWrapItemBean> perPageList = new ArrayList<>();
                            for (AuthorityDistributeItemBean itemBean : list) {
                                perPageList.add(new AuthorityWrapItemBean(itemBean));
                            }
                            mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                            list = new ArrayList<>(); // 清空填装item的容器
                        }
                    }
                    mFragmentList.clear();
                    for (ArrayList<AuthorityWrapItemBean> dataList : mFragmentDataList) {
                        AuthorityDistributeListFragment listFragment = AuthorityDistributeListFragment.newInstance(dataList);
                        listFragment.setOnButtonClickedListener(AuthorityDistributePagerFragment.this);
                        mFragmentList.add(listFragment);
                    }
                    mCustomViewPagerInternal.removeAllViews();
                    mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                    mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                    mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                    mViewPagerAdapter.notifyDataSetChanged();
                    refreshButtonState();
                }
            });
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof AuthorityDistributePagerFragment) {
            mActivity.setTitle("权限分配");
        }
    }

    @Override
    public void requestDatas() {
        if (TextUtils.isEmpty(mBusinessUnitId)) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("authorityType", 3);
        map.put("businessUnitId", mBusinessUnitId);
        mStateLayout.showProgressView(true);
        NoHttpUtils.httpPost(UserCenterConstant.GET_AUTHORITY_BY_BUSI_ID, map, onResponseListener, 0);
    }

    @Override
    public void onButtonClicked() {
        refreshButtonState();
    }

    private void refreshButtonState() {
        mSelectedDataList.clear();
        for (ArrayList<AuthorityWrapItemBean> list : mFragmentDataList) {
            for (AuthorityWrapItemBean wrapItemBean : list) {
                if (wrapItemBean.isSelected) {
                    mSelectedDataList.add(wrapItemBean.mItemBean);
                }
            }
        }
        if (mSelectedDataList.size() > 0) {
            mActivity.setTitle(String.format("权限分配(%d)", mSelectedDataList.size()));
        } else {
            mActivity.setTitle("权限分配");
        }
        mBtnDistribute.setVisibility(mSelectedDataList.size() > 0 ? View.VISIBLE : View.INVISIBLE);
    }
}
